﻿using NCP.Core.DataUtil;
using NCP.Core.IoC;
using NCP.Model;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Data;

namespace NCP.Service
{
    public class DeptMergeInfoService: IService
    {
        private SqlSugarClient _client;
        public DeptMergeInfoService()
        {
            _client = DbHelper.GetSqlSugarClient();
        }

        public DeptMergeInfo Get(string deptCode)
        {
            return _client.Queryable<DeptMergeInfo>().Where(t => t.DeptCode == deptCode).First();
        }

        public List<DeptInfo> GetAllDepts()
        {
            return _client.Queryable<DeptInfo>().Where(t=>t.ValidFlag=="1" && "1,2".Contains(t.DeptType)).ToList();
        }

        public int Compare(string mergeCode, List<DeptCompare> comparelist)
        {
            _client.BeginTran();
            try
            {
                _client.Deleteable<DeptCompare>().Where(t=>t.MergeDeptCode==mergeCode).ExecuteCommand();
                _client.Insertable<DeptCompare>(comparelist).ExecuteCommand();
                _client.CommitTran();
            }
            catch (Exception e)
            {
                _client.RollbackTran();
                return 0;
            }
            return 1;
        }

        public List<DeptCompare> GetDeptCompares(string mergeCode)
        {
            return _client.Queryable<DeptCompare>().Where(t => t.MergeDeptCode == mergeCode).ToList();
        }

        public int Save(DeptMergeInfo item)
        {
            if (string.IsNullOrEmpty(item.DeptCode))
            {
                string deptCode = _client.Queryable<DeptMergeInfo>().Max(t => t.DeptCode);
                if (string.IsNullOrEmpty(deptCode))
                {
                    item.DeptCode = "HB0001";
                }
                else
                {
                    item.DeptCode = "HB" + (deptCode.Substring(2).ObjToInt() + 1).ToString().PadLeft(4,'0');
                }
                return _client.Insertable<DeptMergeInfo>(item).ExecuteCommand();
            }
                
            if (_client.Queryable<DeptMergeInfo>().Where(t => t.DeptCode == item.DeptCode).Count() > 0)
            {
                return _client.Updateable<DeptMergeInfo>(item).Where(t => t.DeptCode == item.DeptCode).ExecuteCommand();
            }
            return 0;
        }

        public int Del(string deptCode) {
            if (string.IsNullOrEmpty(deptCode))
                return 0;
            _client.BeginTran();
            try
            {
                _client.Deleteable<DeptMergeInfo>().Where(t => t.DeptCode == deptCode).ExecuteCommand();
                _client.Deleteable<DeptCompare>().Where(t=>t.MergeDeptCode==deptCode).ExecuteCommand();
                _client.CommitTran();
            }
            catch (Exception e)
            {
                _client.RollbackTran();
                return 0;
            }
            return 1;
        }

        public List<DeptMergeInfo> GetPageList(Expressionable<DeptMergeInfo> whereExpression, PageModel page, string orderFields = "DeptCode")
        {
            int count = 0;
            var result = _client.Queryable<DeptMergeInfo>().Where(whereExpression.ToExpression()).OrderBy(orderFields).ToPageList(page.PageIndex, page.PageSize, ref count);
            page.TotalCount = count;
            return result;
        }

        public virtual List<DeptMergeInfo> GetAll(Expressionable<DeptMergeInfo> exp, string orderFields = "DeptCode")
        {
            return _client.Queryable<DeptMergeInfo>().Where(exp.ToExpression()).OrderBy(orderFields).ToList();
        }

        public List<MissionDept> GetMissionDeptList(string GpCode,string DrugCode)
        {
            List<DeptMergeInfo> mergeDeptList= _client.Queryable<DeptMergeInfo>().OrderBy("DeptCode").ToList();
            List<DeptInfo> deptList = _client.Queryable<DeptInfo>().Where(t => t.ValidFlag == "1" && "1,2".Contains(t.DeptType)).OrderBy("DeptCode").ToList();
            List<DeptCompare> compareList = _client.Queryable<DeptCompare>().ToList();
            List<GroupMission> groupMissions = _client.Queryable<GroupMission>().Where(t => t.GpCode == GpCode && t.DrugCode == DrugCode).ToList();
            mergeDeptList.RemoveAll(t => groupMissions.Exists(g => g.DeptCode == t.DeptCode));
            deptList.RemoveAll(t => groupMissions.Exists(g => g.DeptCode == t.DeptCode));
            deptList.RemoveAll(t => compareList.Exists(g => g.DeptCode == t.DeptCode));

            List<MissionDept> missionDeptList = new List<MissionDept>();
            mergeDeptList.ForEach(t=> {
                missionDeptList.Add(new MissionDept(t));
            });

            deptList.ForEach(t => {
                missionDeptList.Add(new MissionDept(t));
            });
            return missionDeptList;
        }

        public bool Exists(string code)
        {
            int count = _client.Queryable<DeptMergeInfo>().Where(t => t.DeptCode == code).Select<string>(t => t.DeptCode).Count();
            if(count==0)
                count = _client.Queryable<DeptInfo>().Where(t => t.DeptCode == code).Select<string>(t => t.DeptCode).Count();
            return count==1;
        }
        public DataTable export()
        {
            var data = _client.SqlQueryable<DeptInfo>(@"select o.DeptCode,o.DeptName from DeptMergeInfo o 
 where o.ValidFlag=1
 union all
 select f.DeptCode,f.DeptName from DeptInfo f 
 where f.DeptCode not in (select r.DeptCode from DeptCompare r where r.ValidFlag=1)
 and f.DeptType<>'3'")
 .Select<dynamic>(t=>new
 {
     科室编码=t.DeptCode,
     科室名称=t.DeptName
 })
 .ToDataTable();

            return data;
        }
    }
}
